package com.hqd.ch03.v30.web.servlet;


import com.hqd.ch03.v30.context.stereotype.Controller;
import com.hqd.ch03.v30.web.bind.annotation.RequestMapping;
import org.reflections.Reflections;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DispatcherServlet extends HttpServlet {
    private static final Map<String, Method> map = new ConcurrentHashMap<>();
    private static final String PREFIX = "/views/";
    private static final String SUFFIX = ".jsp";

    /**
     * 扫描所有的注册器
     *
     * @param config
     */
    private void scanController(ServletConfig config) {
        Reflections reflections = new Reflections("com.hqd.ch03.test.web");
        /**
         * 根据对应注解，扫描对应的的类
         */
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Controller.class);
        for (Class<?> clazz : classes) {
            Method[] declaredMethods = clazz.getDeclaredMethods();
            /**
             * 扫描对应的RequestMapping
             */
            Arrays.stream(declaredMethods).forEach(m -> {
                RequestMapping rm = m.getAnnotation(RequestMapping.class);
                map.put(rm.value()[0], m);
            });
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        scanController(config);
    }

    protected void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String servletPath = req.getServletPath();
        /**
         * 找到对应的方法
         */
        Method method = map.get(servletPath);
        if (method != null) {
            try {
                Object o = method.getDeclaringClass().getConstructor().newInstance();
                Object result = method.invoke(o, req, resp);
                if (result instanceof String) {
                    String jsp = PREFIX + result + SUFFIX;
                    RequestDispatcher dispatcher = req.getRequestDispatcher(jsp);
                    dispatcher.forward(req, resp);
                }
            } catch (Exception e) {
                resp.sendError(500);
            }

        } else {//找不到对应的请求
            resp.sendError(404);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }
}
